/*
 * Class contains GUI and methods for creating a new User in
 * the login screen
 */
package btracker;

import java.awt.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.*;

/**
 *
 * @version Feb 25 2010
 * @author Sammy Guergachi
 */
public class NewUser {

    static JPasswordField txtConfirm;
    static JLabel lblConfirm;
    static JLabel lblDirectory;
    static JTextField txtDirectory;
    static boolean check;

    public static void newUserGUI() throws InterruptedException, InstantiationException, ClassNotFoundException, IllegalAccessException, UnsupportedLookAndFeelException, IOException {

        if (Login.lblPassWord.getText().equals("Password")) {




            //expand Frame

            for (int i = 200; i <= 390; i = i + 50) {
                Thread.sleep(90);
                Login.loginFrame.setSize(450, i);
            }

            //Change Text 
            Login.btnNewPassword.setText("Accept");
            Login.btnLogIn.setEnabled(false);
            Login.lblPassWord.setText("New Password");
            Login.lblUserName.setText("New User Name");
            Login.lblTitle.setText("Please Create Your New Account");
            Login.btnCancel.setText("Back");



            //New components
            txtConfirm = new JPasswordField();
            lblConfirm = new JLabel("Confirm Password");
            lblDirectory = new JLabel("Project Path");
            txtDirectory = new JTextField();

            Login.pnlTextField.setLayout(new GridLayout(4, 2, 0, 10));
            //Add
            Login.pnlTextField.add(lblConfirm);
            Login.pnlTextField.add(txtConfirm);
            Login.pnlTextField.add(lblDirectory);
            Login.pnlTextField.add(txtDirectory);



        } else {

            check = checkInput(); //Verify Information



            ///Shrink Frame
            for (int i = 300; i >= 200; i = i - 50) {
                Thread.sleep(90);
                Login.loginFrame.setSize(450, i);

            }

            //Remove all text fields

            Login.pnlTextField.removeAll();


            Login.pnlTextField.setLayout(new GridLayout(2, 2, 0, 10));
            //re-add text fields
            Login.pnlTextField.repaint();
            Login.pnlTextField.add(Login.lblUserName);
            Login.pnlTextField.add(Login.txtUserName);
            Login.pnlTextField.add(Login.lblPassWord);
            Login.pnlTextField.add(Login.txtPassWord);



            ///Change text
            Login.btnCancel.setText("Cancel");
            Login.btnNewPassword.setText("New User");
            Login.btnLogIn.setEnabled(true);
            Login.lblPassWord.setText("Password");
            Login.lblUserName.setText("User Name");
            Login.lblTitle.setText("Please Login With Your User Name And Password");





        }
        NewUser.createFiles();
    }

    public static boolean checkInput() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, FileNotFoundException {

        boolean checktxt;

        Login.txtPassWord.getPassword().toString().trim();
        txtConfirm.getPassword().toString().trim();



        if (Arrays.equals(Login.txtPassWord.getPassword(), txtConfirm.getPassword())) {

            //check if password and confirm password are the same
            if (Login.convertPassword(Login.txtPassWord.getPassword()).equalsIgnoreCase("") || Login.convertPassword(txtConfirm.getPassword()).equalsIgnoreCase("") || txtDirectory.getText().equalsIgnoreCase("")) {
                JOptionPane.showMessageDialog(Login.loginFrame, "Please Input Your new Password and or the Directory", null, 0);

                checktxt = false;
            } else {
                checktxt = true;

            }
        } else {
            JOptionPane.showMessageDialog(Login.loginFrame, "Please make sure both passwords the same", null, 0);
            txtConfirm.setText("");
            Login.txtPassWord.setText("");
            checktxt = false;
        }


        //Check if directory exist
        if (checkFile(txtDirectory.getText()) == true && checktxt == true) {

            System.out.println("Checked Confirm");
            checktxt = true;
        } else {
            JOptionPane.showMessageDialog(Login.loginFrame, "Please check to make sure the correct dirrectory is inputed", null, 0);
            txtDirectory.setText("");
            checktxt = false;
        }

        //Check if user name already exist
        FileReader checkUser = new FileReader("directory.ini");
        Scanner read = new Scanner(checkUser);
        int count = 1;

        while (read.hasNext() == true) {
            if (read.nextLine().equalsIgnoreCase(Login.txtUserName.getText()) && checktxt == true) {

                Login.txtUserName.setText("");
                checktxt = false;

                break;
            } else {
                read.nextLine();

                count = count + 1;
                System.out.println("Checked Line");
            }
        }

        if (count <= 1) {

            checktxt = true;
        } else {
            checktxt = false;
            System.out.println("Checked Confirm Already Exist");
            JOptionPane.showMessageDialog(Login.loginFrame, "User Name allready exists!", null, 0);
        }

        return checktxt;
    }

    public static void createFiles() throws IOException {




        if (check == true) {


            //create Project Folder
            String dir = txtDirectory.getText() + "\\" + Login.txtUserName.getText() + "'s Project Folder";

            FileWriter directory = new FileWriter("directory.ini", true);
            BufferedWriter write1 = new BufferedWriter(directory);

            //write directory data into a local file
            write1.append(Login.txtUserName.getText());

            write1.newLine();

            write1.append(dir);

            write1.newLine();

            write1.close();

            File folder = new File(dir);


            //|||||||||||||||Check if Folder Exists
            boolean dirExist = false;
            try {

                if (folder.mkdir()) {
                    System.out.println("Directory Created");
                    JOptionPane.showMessageDialog(Login.loginFrame, "Your new account has been created");
                    dirExist = true;
                } else {
                    System.out.println("Directory is not created");
                    checkInput();
                    dirExist = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (dirExist == true) {

                ///////////////////////////////////////
                // WRITE LOGIN INFORMATION TO UserData///
                //////////////////////////////////////

                FileWriter userData = new FileWriter(dir + "\\UserData.data");
                BufferedWriter write2 = new BufferedWriter(userData);

                String[] password = Crypt.encrypt(Login.convertPassword(txtConfirm.getPassword()));
                String key = password[0]; //index key
                String pass = password[1];//encrypted password

                write2.write(Login.txtUserName.getText());

                write2.newLine();

                write2.write(key);

                write2.newLine();

                write2.write(pass);

                write2.newLine();

                write2.write("new");

                write2.close();

                //////////////////////////////////
                ///Create New Files in Directory///
                //////////////////////////////////

                FileWriter createDataBase = new FileWriter(dir + "\\DataBase.db");
                                
                FileWriter createReport = new FileWriter(dir + "\\ReportData.data");
                FileWriter createCategory = new FileWriter(dir + "\\CategoryData.data");
            }
            Login.txtUserName.setText("");
            Login.txtPassWord.setText("");
            txtConfirm.setText("");
            check = false;
        }
    }

    public static boolean checkFile(String fileName) {
        boolean Exists = false;
        File f = new File(fileName);
        if (f.exists()) {
            Exists = true;
        } else {
        }

        System.out.println(f + (f.exists() ? " is found " : " is missing "));

        return Exists;
    }
}
